package uestc.lj.gulishop.search.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import uestc.lj.common.to.SkuEsModel;
import uestc.lj.gulishop.search.config.GulishopElasticSearchConfig;
import uestc.lj.gulishop.search.constant.EsConstant;
import uestc.lj.gulishop.search.service.ProductSaveService;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Resource
    private RestHighLevelClient restHighLevelClient;

    Logger log = LoggerFactory.getLogger(ProductSaveServiceImpl.class);

    @Override
    public boolean productStatusUP(List<SkuEsModel> skuEsModels) throws IOException {
        // 1.给es中建立索引并且建立好映射关系
        // 2.给es中保存这些数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulishopElasticSearchConfig.COMMON_OPTIONS);

        List<String> list = Arrays.stream(bulk.getItems())
                .map(BulkItemResponse::getId)
                .collect(Collectors.toList());
//        System.out.println("商品上架完成！" + list);
        log.info("商品上架完成！{}", list);
        return bulk.hasFailures();
    }
}
